package la.foton.atividade.service;

import javax.persistence.EntityManager;
import javax.persistence.NoResultException;
import javax.persistence.PersistenceContext;

import la.foton.atividade.entity.Usuario;

import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

@Component("userDetailsService")
public class UserDetailsServiceImpl implements UserDetailsService {

	@PersistenceContext
	private EntityManager entityManager;

	public UserDetails loadUserByUsername(String username)
			throws UsernameNotFoundException {
		return findByUsername(username);
	}

	private Usuario findByUsername(String username) {
		try {

			return (Usuario) entityManager
					.createNamedQuery("Usuario.findByUsername")
					.setParameter("login", username).getSingleResult();

		} catch (NoResultException e) {
			throw new UsernameNotFoundException("Usuario nao encontrado");
		}
	}
}
